<?php

namespace backend\grid;

use backend\assets\plugins\SwitcherAsset;
use Closure;
use common\libs\Constants;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;

class MySwitcherColumn extends DataColumn
{
    public $ModelClass;
    public $Model;

    public $LinkModelClass;
    public $LinkModel;

    public $LinkAction;
    public $LinkParams;

    public $ViaModel;
    public $ViaKey = 'dept_id';
    public $ViaVal = 'id';

    public $Controller;

    public $Url;
    public $reload = '0';

    /**
     * {@inheritdoc}
     */
    protected function renderDataCellContent($model, $key, $index)
    {
        $value = $this->getDataCellValue($model, $key, $index);
        if (is_string($value) && !in_array($value, [0, '0', 1, '1', true, 'true', false, 'false'], true)) {
            $result = $value;
        } else {
            $this->registerClientScript();
            $result = Html::checkbox(
                $this->attribute,
                Constants::YesNo_Yes == $value,
                [
                    'class'           => 'js-switch',
                    //'data-method' => 'post',// @todo 加上这个导致页面发生跳转,所以要注释!!!!!
                    'data-pjax'       => true,
                    'data-url'        => $this->getUrl($model, $key, $index),
                    'data-params'     => [
                        'ModelClass'     => $this->getModelClass($model, $key, $index),
                        'Modelid'        => $key,
                        'LinkModelClass' => $this->getLinkModelClass($model, $key, $index),
                        'LinkModelid'    => $this->LinkModel->id,
                        'LinkParams'     => $this->LinkParams,
                        'LinkAction'     => $this->getLinkAction($model, $key, $index),
                        'ViaModel'       => $this->ViaModel,
                        'ViaKey'         => $this->ViaKey,
                        'ViaVal'         => $this->ViaVal,
                    ],
                    'data-reload'     => $this->reload,
                    'data-linkaction' => $this->getLinkAction($model, $key, $index),
                    'data-toggle'     => 'switcher',
                    'data-input'      => 'input_score_'.$key,
                    'switcher-size'   => 'small',
                ]
            );
        }

        return $result;
    }

    public function registerClientScript()
    {
        SwitcherAsset::register($this->grid->view);
        $js = <<< JS
            $(function () {
                var elems = Array.prototype.slice.call(document.querySelectorAll('[data-toggle=switcher]'));
                elems.forEach(function (html) {
                    var disabled = !!$(html).data('switcher-disabled');
                    var size = $(html).data('switcher-size') || 'small';
                    var switchery = new Switchery(html, {size: size, disabled: disabled, disabledOpacity: 0.5});
                    $(html).data('switchery', switchery);
                });
            });
            $('.js-switch').on('change', function(){
                var obj=$(this);
                var switchery =  obj.data("switchery");
                var url =  obj.data("url");
                var data = obj.data("params");
                data.LinkAction=obj.data("linkaction");
                var reload =  obj.data("reload");
                var input =$('#'+obj.data("input"));
                var field=input.data("field");
                var oldval=input.data(field);
                if(!data.LinkParams){
                    data.LinkParams={score:input.val() };
                }
                $.ajax({
                    "url": url,
                    "data":data,
                    "dataType": "json",
                    "type": 'post',
                    'beforeSend': function () {
                        layer.load(2, {
                            shade: [0.1, '#fff'] //0.1透明度的白色背景
                        });
                    },
                    "success": function (data) {
                         var link=obj.data("linkaction");
                        if(input.hasClass('hidden')){
                            input.removeClass("hidden");
                            input.data("id",data.id);
                        }else{
                            input.addClass("hidden");
                            input.val(oldval);
                        }
                        if(link=='link'){
                           obj.data("linkaction",'unlink');
                        }
                        if(link=='unlink'){
                           obj.data("linkaction",'link');
                        }

                        layer.msg(data.message,{time:400});
                        if(reload){
                            location.reload();
                        }
                    },
                    "error": function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR.responseJSON.message);
                    },
                    "complete": function () {
                        layer.closeAll('loading');
                    }
                });
            });

        /*
         * 切换Switchery开关函数
         * switchElement Switchery对象
         * checkedBool 选中的状态
         */
        function setSwitchery(switchElement, checkedBool) {
            if ((checkedBool && !switchElement.isChecked()) || (!checkedBool && switchElement.isChecked())) {
                switchElement.setPosition(true);
                switchElement.handleOnchange(true);
            }
        }
JS;
        $this->grid->view->registerJs($js, View::POS_READY); //因为可能会被pjax加载所以放在这里
    }

    private function getUrl($model, $key, $index)
    {
        //根据当前类名获取Controller
        if (empty($this->Url)) {
            $Controller = $this->getController($model, $key, $index);
            $this->Url  = Url::to(['/'.$Controller.'/link', 'id' => $key]);
        }

        return $this->Url;
    }

    private function getController($model, $key, $index)
    {
        if (!empty($this->Controller)) {
            $Controller = $this->renderCallback($this->Controller, [$model, $key, $index, $this]);
        } else {
            $Controller = end(explode('\\', $model->className()));
        }

        return strtolower($Controller);
    }

    protected function renderCallback($Callback, $parameter = [])
    {
        if (is_string($Callback)) {
            $res = $Callback;
        }
        if ($Callback instanceof Closure) {
            $res = call_user_func_array($Callback, $parameter);
        }

        return $res;
    }

    protected function getModelClass($model, $key, $index)
    {
        if (!empty($this->ModelClass)) {
            $ModelClass = $this->renderCallback($this->ModelClass, [$model, $key, $index, $this]);
        } else {
            if (!empty($this->Model)) {
                $ModelClass = $this->Model->className();
            } else {
                $ModelClass = $model->className();
            }
        }

        return $ModelClass;
    }

    protected function getLinkModelClass($model, $key, $index)
    {
        if (!empty($this->LinkModelClass)) {
            $LinkModelClass = $this->renderCallback($this->LinkModelClass, [$model, $key, $index, $this]);
        } else {
            if (!empty($this->LinkModel)) {
                $LinkModelClass = $this->LinkModel->className();
            } else {
                $LinkModelClass = $model->className();
            }
        }

        return $LinkModelClass;
    }

    protected function getLinkAction($model, $key, $index)
    {
        if (!empty($this->LinkAction)) {
            $LinkAction = $this->renderCallback($this->LinkAction, [$model, $key, $index, $this]);
        } else {
            throw new \Exception('LinkAction 必须设置', '500');
        }

        return $LinkAction;
    }

    protected function getLinkModel($model, $key, $index)
    {
        if (!empty($this->LinkModel)) {
            $LinkModel = $this->renderCallback($this->LinkModel, [$model, $key, $index, $this]);
        } else {
            throw new \Exception('LinkModel 必须设置', '500');
        }

        return $LinkModel;
    }
}
